﻿package motor.grafico {
	
	import flash.events.*;
	import flash.display.*;
	import reglas.*;
	import reglas.entidades.*;
	
	public class Grafico extends EventDispatcher implements IEntidadObserver 
	{
		
		public static const EVENTO_CLICK:String = "EVENTO_CLICK";
		
		protected var bitmap:Bitmap;
		
		
		private var graficoX:Number;
		private var graficoY:Number;
		
		private var graficoVX:Number;
		private var graficoVY:Number;
		
		private var lastTimeUpdate:uint;
		
		
		public function Grafico(unEscenario:Sprite)
		{
			bitmap = getDefaultBitmap();			
			
			//bitmap.addEventListener(MouseEvent.CLICK, clickGrafico);
			
			agregarGraficoEscenario(unEscenario);
			
			bitmap.addEventListener(Event.ENTER_FRAME,animar);
		}
		
		protected function getDefaultBitmap():Bitmap
		{
			var cantidadTotal:int = 4;
			var bitmapRet:Bitmap = null;
			var index:int = Math.random()*100;
			
			index = index % 4;
			
			switch (index) {
				case 0:
					bitmapRet = new Bitmap(new Nave64(1,1));
				break;
				case 1:
					bitmapRet = new Bitmap(new Nave2_64(1,1));
				break;
				case 2:
					bitmapRet = new Bitmap(new Nave3(1,1));
				break;
				case 3:
					bitmapRet = new Bitmap(new Nave4(1,1));
				break;
			}		
			
			return bitmapRet;
		}
		
		private function agregarGraficoEscenario (unEscenario:Sprite)
		{
			unEscenario.addChild(bitmap);			
		}
		
		private function quitarGraficoEscenario (unEscenario:Sprite)
		{
			unEscenario.removeChild(bitmap);
		}
		
		/*
		public function clickGrafico (event:MouseEvent)
		{
			dispatchEvent(new Event(Grafico.EVENTO_CLICK));
		}*/
		
		public function update (nuevoEstado:int, posX:Number, posY:Number, vx:Number, vy:Number)
		{
			if (nuevoEstado==EntidadControladaMovimiento.ESTADO_DESTROY)
			{
				destroy();
				return;
			}
			//----
			lastTimeUpdate = Universo.getInstancia().getTiempoUniversal();
			//----
			graficoX = posX;
			graficoY = posY;
			graficoVX = vx;
			graficoVY = vy;			
		}
		
		public function animar (e:Event)
		{
			
			//var currentDate:Date = new Date();
			var currentMS:Number = Universo.getInstancia().getTiempoUniversal();
			var dt:Number = (currentMS-lastTimeUpdate)/1000;
			
			bitmap.x = graficoX + graficoVX*dt;
			bitmap.y = graficoY + graficoVY*dt;
		}
		
		public function destroy ()
		{
			quitarGraficoEscenario(Graficos.getInstancia().getEscenario());
			//bitmap.removeEventListener(MouseEvent.CLICK, clickGrafico);
			bitmap.removeEventListener(Event.ENTER_FRAME,animar);
		}
		
	}
}